
from __future__ import absolute_import
from __future__ import print_function
#from __future__ import unicode_literals
from __future__ import division


'''
        @author: msune,  lbergesio, cbermudo, omoya

    Simple example to emulate Server/client side interaction

'''


#from pelib.ruletable import RuleTable

from pelib.utils import logging

import mypolicyengine
from interface import interface

logger = logging.get_logger()

def addRuleAndDump(rule):
    if rule:
        logger.info("\nAdding a Rule to Policy Engine")
        mypolicyengine.get_policy().addRule(rule)
    logger.info("\nDumping table state...")
    logger.info("[RULETABLE]######################################################################")
    mypolicyengine.dump()
    logger.info("[RULETABLE]######################################################################\n")

def call(message, cred, xml):
    #Simulating throwing first query to the interface
    logger.info("%s", message)
    logger.info("Message: ope")
    try:
        logger.info("Simulating query...")
        interface.remoteMethod(cred,  xml)
    except Exception, e:
        logger.error("Query failed")
        logger.error(str(e))

    logger.info("-----")

'''
    Simulating instantiation of main engine,  to call interface afterwards
'''
logger.info("Dumping inital table state...\n")
addRuleAndDump(None)

addRuleAndDump("if ( vm.RAM < 512 ) then accept do log denyMessage Memory is greater than 512 MB #Preventing VMs with more than 512 MB")

'''
    Simulating client
'''
#Generating requests
credential = {'CA':'i2CAT', 'user':'lbergesio'}
ope = open('interface/example1.xml', 'r').read()
ope2 = open('interface/example2.xml', 'r').read()



call("First query", credential, ope)
call("Second query", credential, ope2)

addRuleAndDump("if ( vm.RAM > 128 ) && (user.id = lbergesio) then deny denyMessage User is not able to instantiate VMs with more than 128 MB of memory #lbergesio specific rule")
logger.info("Now moving rule on top (will forbbid user)")
mypolicyengine.get_policy().moveRule(0, index=1)
addRuleAndDump(None)

call("Third query", credential, ope)

